package cz.none.bezbarier.web.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

public abstract class ARepository<Model> {
	@PersistenceContext
	private EntityManager em;

	/**
	 * Method for easier paging of model objects
	 *
	 * @param select
	 *            SQL query for selecting object
	 * @param count
	 *            SQL query for getting count of all object corresponding to
	 *            previous query
	 * @param clazz
	 *            Type of selected objects (for type safety)
	 * @param pageable
	 *            Information about requested page (offset & page size)
	 * @param params
	 *            parameters for SQL queries (used for both select and count
	 *            query)
	 * @return Page of right objects according class and selection parameters
	 */
	protected Page<Model> findByQuery(String select, String count, Class<Model> clazz, Pageable pageable,
			Object... params) {
		Long total = setParameters(em.createQuery(count, Long.class), params).getSingleResult();

		List<Model> content = setParameters(em.createQuery(select, clazz), params)
				.setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList();

		return new PageImpl<Model>(content, pageable, total);

	}

	private <T> TypedQuery<T> setParameters(TypedQuery<T> query, Object... parameters) {
		int i = 1;
		for (Object object : parameters) {
			query.setParameter(i, object);
			i++;
		}
		return query;

	}

}
